package com.kehutong.wwin.service.controller;

import com.kehutong.common.DoveClient;
import com.kehutong.common.entity.Root;
import com.kehutong.common.util.Token;
import com.kehutong.wwin.service.entity.Corp;
import com.kehutong.wwin.service.entity.DepartmentMap;
import com.kehutong.wwin.service.entity.EmployeeMap;
import com.kehutong.wwin.service.service.*;
import com.kehutong.wwin.service.util.WwInHttpClient;
import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.IDGenerate;
import org.coraframework.util.Objects;
import org.coraframework.util.secret.Base64Coder;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@MvcAction
@ReqMapping("/admin/wwin/corp")
public class CorpController {
	
	static final Logger logger = LoggerFactory.getLogger(CorpController.class);
	
	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private ToKhtDepartmentService khtepartmentService;
	@Inject
	private ToWwinDepartmentService wwinDepartmentService;
	@Inject
	private ToKhtEmployeeService khtEmployeeService;
	@Inject
	private ToWwinEmployeeService wwinEmployeeService;
	@Inject
	private WwInHttpClient httpClient;

	@Inject
	private ToKhtResidentService toKhtResidentService;

	@Inject
	private ToKhtTagService toKhtTagService;

	@Inject
	private WxApiService wxApiService;

	@Inject
	private DoveClient doveClient;
	
	@HasPermission("wwin:corp:view")
    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) {
		return jdbcSession.findPage(Corp.class)
				.eq(jsonObject, "id")
				.like(jsonObject, "corpName")
				.eq("deleted", false)
				.page(jsonObject)
				.exe();
    }
	
    @HasPermission("wwin:corp:view")
    @ReqMapping("/get")
    public Object get(Corp item) {
    	return item;
    }
    
    @Bean(newInstance=true, copy=true)
    @HasPermission("wwin:corp:edit")
    @ReqMapping("/save")
    public Object save(Corp item) throws Exception {
    	jdbcSession.insert(item);
    	return Result.success(item);
    }
    
    @Bean(copy=true)
    @HasPermission("wwin:corp:edit")
    @ReqMapping("/update")
    public Object update(Corp item) throws Exception {
    	
    	jdbcSession.updateById(item);
    	return Result.success(item);
    }

    @HasPermission("wwin:corp:edit")
    @ReqMapping("/delete")
    public Object delete(Corp item) throws Exception {
    	if (Objects.nonNull(item)) {
    		item.setDeleted(true);
    		jdbcSession.updateById(item);
    	}
    	
    	return Result.success();
    }
    
    //@HasPermission("wwin:department:edit")
    @ReqMapping("/department/syn")
    public Object sysDepartment(Token token) throws Exception {
		JSONObject rs = wwinDepartmentService.listDepartment(token);
		int result = rs.getIntValue("errcode");
		if (result != 0) {
			logger.error("batch save department err: code={}, errmsg", result, rs.getString("errmsg"));
			return Result.error(result, rs.getString("errmsg"));
		}
		
		
		JSONArray jsonArray = rs.getJSONArray("department");

		//获取第三方同步部门映射主键,防止产生重复数据
		//首次同步第三方映射数据，保持内建与第三方的数据一致
		Map<String, String> thridMap=khtepartmentService.getDepartmentMap();
		for (int i = 0; i < jsonArray.size(); i ++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			
			int id = jsonObject.getInteger("id");
			jsonObject.remove("id");
			DepartmentMap map = khtepartmentService.getDepartmentByWwId(id);
			if (Objects.isNull(map)) {
				map = Pool.newInstance(DepartmentMap.class, String.valueOf(id));
				map.setKhtid(Root.isRoot(map.getId()) ? map.getId() :ToKhtDepartmentService.buildDeptKhtId(thridMap,token.getCompanyNo(),String.valueOf(id)));
				khtepartmentService.save(map);
			}
			
			int pid = jsonObject.getIntValue("parentid");
			if (pid != 0) {
				DepartmentMap parent = khtepartmentService.getDepartmentByWwId(pid);
				jsonObject.put("parent_id", parent.getKhtid());
			}
			
			jsonObject.put("id", map.getKhtid());
			jsonObject.put("name", (String)jsonObject.remove("name"));
			jsonObject.put("sort", (Integer)jsonObject.remove("order"));
			//公司模板 0.第三方 1.内建
			jsonObject.put("pattern","1");

		}
		
		JSONObject jsonRs = httpClient.postKht("/basic/department/service/saveBatch", token, http->{
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("departments", jsonArray);
			http.setBody(jsonObject.toJSONString());
		});
		
		return Result.error(jsonRs.getIntValue("code"), jsonRs.getString("message"));
    }


    
    //@HasPermission("wwin:employee:edit")
    @ReqMapping("/employee/syn")
    public Object syneEployee(Token token) throws Exception {
		JSONObject rs = wwinEmployeeService.listEmployee(token);
		int result = rs.getIntValue("errcode");
		if (result != 0) {
			logger.error("batch save employee err: code={}, errmsg", result, rs.getString("errmsg"));
			return Result.error(result, rs.getString("errmsg"));
		}
		
		
		JSONArray jsonArray = rs.getJSONArray("userlist");
		
		for (int i = 0; i < jsonArray.size(); i ++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			
			String userId = jsonObject.getString("userid");
			EmployeeMap map = khtEmployeeService.getEmployeeByWwId(userId);

			String username = jsonObject.getString("userid");
			if (Objects.isNull(map)) {
				map = Pool.newInstance(EmployeeMap.class, userId);
				map.setKhtid(ToKhtEmployeeService.toKhtId(token.getCompanyNo(), userId));
				map.setAvatar(jsonObject.getString("avatar"));
				map.setUserId(userId);
				map.setName(jsonObject.getString("name"));
				map.setQrCode(jsonObject.getString("qr_code"));
				khtEmployeeService.save(map);
			}else{
				map.setAvatar(jsonObject.getString("avatar"));
				map.setName(jsonObject.getString("name"));
				map.setQrCode(jsonObject.getString("qr_code"));
				jdbcSession.updateById(map);
			}

			String name = jsonObject.getString("name");

			//主部门
			String main_department = jsonObject.getString("main_department");

			//成员所属部门id列表，仅返回该应用有查看权限的部门id
			JSONArray department = jsonObject.getJSONArray("department");

			//是否为上级
			String identity="0";
			//表示在所在的部门内是否为上级
			JSONArray isLeaderInDept = jsonObject.getJSONArray("is_leader_in_dept");
			if(Objects.nonEmpty(isLeaderInDept)){
				for (int x  = 0; x < isLeaderInDept.size(); x ++) {
					String isLeader=isLeaderInDept.getString(x);
					if(Objects.equal("1",isLeader)){
						identity="1";
						break;
					}
				}
			}

			String mobile = jsonObject.getString("mobile");
			String gender = jsonObject.getString("gender");
			String email = jsonObject.getString("email");
			String avatar = jsonObject.getString("avatar");
			String address = jsonObject.getString("address");
			String qrCode = jsonObject.getString("qr_code");
			jsonObject.clear();
			
			jsonObject.put("id", map.getKhtid());
			jsonObject.put("username", username);
			jsonObject.put("name", name);
			jsonObject.put("qrCode", qrCode);
			jsonObject.put("nickname", name);
			jsonObject.put("avatar", avatar);
			jsonObject.put("gender", gender);
			jsonObject.put("mobile", mobile);
			jsonObject.put("email", email);
			jsonObject.put("address", address);
			jsonObject.put("department", khtepartmentService.toKhtId(department));
			//jsonObject.put("departments", khtepartmentService.toKhtId(department));
            //TODO 需要是否为上级
			jsonObject.put("identity",identity);
			jsonObject.put("mainDepartment",khtepartmentService.toKhtId(main_department));
		}
		
		JSONObject jsonRs = httpClient.postKht("/basic/employee/service/saveInnerBatch", token, http->{
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("companyNo", token.getCompanyNo());
			jsonObject.put("companyName", token.getCompanyName());
			jsonObject.put("userList", jsonArray);
			http.setBody(jsonObject.toJSONString());
		});
		
		return Result.error(jsonRs.getIntValue("code"), jsonRs.getString("message"));
    }

	/**
	 * 批量同步企业微信客户数据到客户通业主信息表中
	 * @param token 用户信息
	 * @return 返回结果
	 * @throws Exception 异常信息
	 */
	@HasPermission("wwin:resident:sync")
	@ReqMapping("/resident/syn")
	public Object syncResident(Token token) throws Exception {
		return toKhtResidentService.syncResident(token);
	}

	/**
	 * 全量同步企业微信客户标签数据到客户通标签信息中
	 * @param token 用户信息
	 * @return 返回结果
	 * @throws Exception 异常信息
	 */
	@HasPermission("wwin:tag:sync")
	@ReqMapping("/tag/syn")
	public Object syncTag(Token token) throws Exception {
		return toKhtTagService.syncTag(token);
	}


	@ReqMapping("/wx/api/test")
	public Object wxApiTest(Token token) throws Exception {
		wxApiService.wxApiTest(token);
		return Result.success();
	}


}
